package se.miun.dt156g.antonsskafferibestallning;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class LunchOrderActivity extends Activity implements OnClickListener {

	private String tableNo;
	private ProgressDialog pDialog;
	private static final String READ_COMMENTS_URL = "http://pellos.no-ip.org/android/lunch.php";
	private static final String POST_COMMENT_URL = "http://pellos.no-ip.org/android/addlunchorder.php";
	private static final String TAG_POSTS = "posts";
	private static final String TAG_MAIN = "lunchName";
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_MESSAGE = "message";
	private JSONArray lunchMenu = null;
	private ArrayList<String> lunchMenuList;
	private Button submit;
	JSONParser jsonParser = new JSONParser();

	HashMap<String, Integer> noOfOrders = new HashMap<String, Integer>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lunch_order);

		new LoadComments().execute();
		Bundle extras = getIntent().getExtras();
		tableNo = Integer.toString(extras.getInt("TableNo"));
		submit = (Button) findViewById(R.id.lunchOrderNextButton);
		submit.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		new PostComment().execute();
	}

	class PostComment extends AsyncTask<String, String, String> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LunchOrderActivity.this);
			pDialog.setMessage("Skickar order...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... args) {
			// TODO Auto-generated method stub
			// Check for success tag
			int success;

			// String post_message = message.getText().toString();

			// We need to change this:
			// SharedPreferences sp =
			// PreferenceManager.getDefaultSharedPreferences(LunchOrderActivity.this);
			// String post_username = sp.getString("username", "anon");

			try {
				// Building Parameters
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("table_no", tableNo));
				for (int i = 0; i < noOfOrders.size(); i++) {
					params.add(new BasicNameValuePair("lunch_name[]",
							lunchMenuList.get(i)));
					params.add(new BasicNameValuePair("lunch_number[]", Integer
							.toString(noOfOrders.get(lunchMenuList.get(i)))));
				}
				Log.d("request!", "starting");

				// Posting user data to script
				JSONObject json = jsonParser.makeHttpRequest(POST_COMMENT_URL,
						"POST", params);

				// full json response
				Log.d("Post Comment attempt", json.toString());

				// json success element
				success = json.getInt(TAG_SUCCESS);
				if (success == 1) {
					Log.d("Comment Added!", json.toString());
					finish();
					return json.getString(TAG_MESSAGE);
				} else {
					Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
					return json.getString(TAG_MESSAGE);

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;

		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog once product deleted
			pDialog.dismiss();
			if (file_url != null) {
				Toast.makeText(LunchOrderActivity.this, file_url,
						Toast.LENGTH_LONG).show();
			}

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.lunch_order, menu);

		return true;
	}

	public void updateJSONdata() {

		// Instantiate the arraylist to contain all the JSON data.
		// we are going to use a bunch of key-value pairs, referring
		// to the json element name, and the content, for example,
		// message it the tag, and "I'm awesome" as the content..

		lunchMenuList = new ArrayList<String>();

		// Bro, it's time to power up the J parser
		JSONParser jParser = new JSONParser();
		// Feed the beast our comments url, and it spits us
		// back a JSON object. Boo-yeah Jerome.
		JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);

		// when parsing JSON stuff, we should probably
		// try to catch any exceptions:
		try {

			// I know I said we would check if "Posts were Avail." (success==1)
			// before we tried to read the individual posts, but I lied...
			// mComments will tell us how many "posts" or comments are
			// available
			lunchMenu = json.getJSONArray(TAG_POSTS);

			// looping through all posts according to the json object returned
			for (int i = 0; i < lunchMenu.length(); i++) {

				JSONObject c = lunchMenu.getJSONObject(i);

				// gets the content of each tag
				// String beverage = c.getString(TAG_BEVERAGE);
				// String starter = c.getString(TAG_STARTER);
				String main = c.getString(TAG_MAIN);
				// String dessert = c.getString(TAG_DESSERT);
				lunchMenuList.add(main);
				noOfOrders.put(c.getString(TAG_MAIN), 0);

				// creating new HashMap
				// HashMap<String, String> map = new HashMap<String, String>();
				//
				// map.put(TAG_BEVERAGE, beverage);
				// map.put(TAG_STARTER, starter);
				// map.put(TAG_MAIN, main);
				// map.put(TAG_DESSERT, dessert);
				// Log.d("testdessert", dessert);
				//
				// // adding HashList to ArrayList
				// lunchMenuList.add(map);

				// annndddd, our JSON data is up to date same with our array
				// list
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void updateList() {
		// For a ListActivity we need to set the List Adapter, and in order to
		// do
		// that, we need to create a ListAdapter. This SimpleAdapter,
		// will utilize our updated Hashmapped ArrayList,
		// use our single_post xml template for each item in our list,
		// and place the appropriate info from the list to the
		// correct GUI id. Order is important here.
		// ListAdapter adapter = new SimpleAdapter(this, lunchMenuList,
		// R.layout.single_post, new String[] { TAG_BEVERAGE, TAG_MAIN,
		// TAG_DESSERT }, new int[] { R.id.title, R.id.message,
		// R.id.dessert });
		MultiSourceAdapter adapter = new MultiSourceAdapter(
				getApplicationContext(), lunchMenuList, noOfOrders);
		// ListAdapter adapter = new SimpleAdapter(this, lunchMenuList,
		// R.layout.single_post, new String[] { TAG_BEVERAGE, TAG_MAIN,
		// TAG_DESSERT }, new int[] { R.id.title, R.id.message,
		// R.id.dessert });

		// I shouldn't have to comment on this one:
		ListView lv = (ListView) findViewById(R.id.lunchOrderListView);
		lv.setAdapter(adapter);

		// Optional: when the user clicks a list item we
		// could do something. However, we will choose
		// to do nothing...
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				noOfOrders.put(lunchMenuList.get(position),
						noOfOrders.get(lunchMenuList.get(position)) - 1);
				updateList();
				return true;
				
			}
			
		});
		lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				noOfOrders.put(lunchMenuList.get(position),
						noOfOrders.get(lunchMenuList.get(position)) + 1);
				updateList();
			}
		});
	}

	public class LoadComments extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(LunchOrderActivity.this);
			pDialog.setMessage("Laddar meny...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		@Override
		protected Boolean doInBackground(Void... arg0) {
			// we will develop this method in version 2
			updateJSONdata();
			return null;

		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			// we will develop this method in version 2
			updateList();
		}
	}

}
